package com.example.bawolf.jms.topic;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * AppConsumer
 *
 * @author zhougf
 * @date 2020/03/10
 */
public class AppConsumer02 {
    public static void main(String[] args) throws JMSException {
        System.out.println("我是接受者2");
        String activeMqUrl = "tcp://49.234.184.233:61616";
        String queueName = "queue01";
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(activeMqUrl);
        Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();
        Session connectionSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = connectionSession.createTopic(queueName);
        MessageConsumer consumer = connectionSession.createConsumer(topic);
        //同步阻塞兴 receive可以设置时间到时间会关闭若不设置则一直等待
//        while (true) {
//            TextMessage receive = (TextMessage) consumer.receive();
//            if(null != receive) {
//                System.out.println("接收到消息：" + receive.getText());
//            } else {
//                break;
//            }
//        }
        //监听模式
        consumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                if(message != null && message instanceof TextMessage){
                    try {
                        TextMessage textMessage = (TextMessage) message;
                        System.out.println("接收到消息" + textMessage.getText());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
        consumer.close();
        connectionSession.close();
        connection.close();
        System.out.println("已接收到消息");
    }
}
